package com.kfm.advice;

import com.kfm.anno.M;
import com.kfm.dao.LogDao;
import com.kfm.entity.Log;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Date;

@Aspect
@Component
public class LogAdvice {

    @Autowired
    private LogDao dao;

    @Pointcut("execution(* com.kfm.service..*.*(..))")
    public void pt(){};

    @Around("pt()")
    public Object around(ProceedingJoinPoint proceedingJoinPoint){
        Object obj = null;
        //方法名
        String methodName = proceedingJoinPoint.getSignature().getName();
       //类名
        String className = proceedingJoinPoint.getTarget().getClass().getName();
        // 类名 + 方法
        String name = className + "." + methodName;

        //时间
        Date start = new Date();
        boolean result = true;

        Log log = new Log();

        try {
            Class<?> aClass = Class.forName(className);
            //参数
            Object[] args = proceedingJoinPoint.getArgs();
            String params = Arrays.toString(args);

            Class[] classes = new Class[args.length];
            for (int i = 0;i<args.length;i++){
                classes[i] = args[i].getClass();
            }
            // 通过反射 获取到执行的 方法
            Method method = aClass.getDeclaredMethod(methodName, classes);
            M annotation = method.getAnnotation(M.class);
            //内容
            String content = annotation.value();

            log.setMethod(name);
            log.setContent(content);
            log.setArgs(params);
            log.setStartTime(start);
            //执行方法

            obj = proceedingJoinPoint.proceed(args);

        } catch (Throwable e) {
            e.printStackTrace();
            result = false;
        } finally {
            // 耗时
            long time = System.currentTimeMillis() - start.getTime();
            log.setResult(result);
            log.setTime(time);
            dao.save(log);
        }
        return obj;
    }
}
